/**
* @Title: MyMessageConvert.java
* @Package com.an.message.conv
* @Description: TODO(用一句话描述该文件做什么)
* @author antch,861710865@qq.com
* @date 2017年7月17日 上午11:08:13
* @version V1.0
*/


package com.an.message.conv;

import java.io.IOException;
import java.nio.charset.Charset;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import com.an.model.Dog;

/**
* @ClassName: MyMessageConvert
* @Description: TODO(处理request、response里面的数据)
* @author antch,861710865@qq.com
* @date 2017年7月17日 上午11:08:13
*
*/

/*
 * 继承AbstractHttpMessageConverter，实现自定义消息转换
 */
@Component
public class MyMessageConvert extends AbstractHttpMessageConverter<Dog> {


	public MyMessageConvert() {
		//新建一个我们自定义的媒体类型application/x-wisely
		super(new MediaType("application","x-wisely" ,Charset.forName("UTF-8")));
	}

	/*
	 * (非 Javadoc)
	* <p>Title: supports</p>
	* <p>Description: 表明只处理Dog这个类</p>
	* @param clazz
	* @return
	* @see org.springframework.http.converter.AbstractHttpMessageConverter#supports(java.lang.Class)
	 */
	@Override
	protected boolean supports(Class<?> clazz) {
		return Dog.class.isAssignableFrom(clazz);
	}

	/*
	 * (非 Javadoc)
	* <p>Title: readInternal</p>
	* <p>Description: 处理请求的数据</p>
	* @param clazz
	* @param inputMessage
	* @return
	* @throws IOException
	* @throws HttpMessageNotReadableException
	* @see org.springframework.http.converter.AbstractHttpMessageConverter#readInternal(java.lang.Class, org.springframework.http.HttpInputMessage)
	 */
	@Override
	protected Dog readInternal(Class<? extends Dog> clazz, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException {
		// TODO Auto-generated method stub
		String temp = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
		String[] tempArr = temp.split("-");
		return new Dog(new Long(tempArr[0]),tempArr[1]);
	}

	@Override
	protected void writeInternal(Dog dog, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		// TODO Auto-generated method stub
		String out = "hello :" + dog.getId() + "-" + dog.getName();
		outputMessage.getBody().write(out.getBytes());
	}

}
